# ocr_server.py
from flask import Flask, request, jsonify
import ddddocr
from PIL import Image
import io

app = Flask(__name__)
ocr = ddddocr.DdddOcr(det=True, rec=True, show_ad=False)


@app.route('/ocr', methods=['POST'])
def ocr_image():
    # 接收图片
    file = request.files['image']
    img = Image.open(io.BytesIO(file.read()))

    # 执行识别
    det_res = ocr.detection(img)
    rec_res = [ocr.classification(img.crop(box)) for box in det_res]

    # 构建返回数据
    result = []
    for (x1, y1, x2, y2), text in zip(det_res, rec_res):
        # 计算中心坐标
        center_x = (x1 + x2) // 2
        center_y = (y1 + y2) // 2
        result.append({
            "text": text,
            "x": int(center_x),
            "y": int(center_y),
            "width": x2 - x1,
            "height": y2 - y1
        })

    return jsonify({"code": 0, "data": result})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)